package com.kingjw.kafka;


import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;


import java.util.Arrays;
import java.util.Map;
import java.util.Properties;


/**
 * @Package: com.kingjw.kafka
 * @ClassName: CustomConsumer
 * @Author: 王坚伟
 * @CreateTime: 2021/10/26 19:46
 * @Description:
 */
public class CustomConsumer {
    public static void main(String[] args) {

        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"hadoop117:9092");
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"test3");
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,"1000");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
        consumer.subscribe(Arrays.asList("first"));
        while (true){
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                System.out.printf("offset = %d,key = %s,value = %s%n",record.offset(),record.key(),record.value());
            }
            consumer.commitAsync(new OffsetCommitCallback() {
                public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception exception) {
                    if (exception != null){
                        System.err.println("Commit failed for "+ offsets);
                    }
                }
            });
        }


    }
}
